package com.github.eden.generator;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

public class TemplateEngine {

    private Configuration configuration;

    public TemplateEngine(String basePath) throws IOException {
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        String path = new File(TemplateEngine.class.getResource(basePath).getFile()).getPath();
        if (path.contains("jar")) {
            configuration.setClassForTemplateLoading(TemplateEngine.class, basePath);
        } else {
            configuration.setDirectoryForTemplateLoading(new File(path));
        }
        configuration.setEncoding(Locale.CHINA, StandardCharsets.UTF_8.name());
    }

    public String render(String fileName, Object params) throws IOException, TemplateException {
        Template template = configuration.getTemplate(fileName);
        StringWriter writer = new StringWriter();
        template.process(params, writer);
        writer.flush();
        return writer.toString();
    }
}
